// pages/order/order.js
const app = getApp()
var api = require('../../utils/api.js')
var util = require('../../utils/util.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    items: [],
    buyPatterns: true,
    invoice: true,
    addressCol: true,
    total_price: "0",
    buy_type: "1",
    buyType: "1",
    invoiceNeed: "0",
    invoiceType: "1",
    invoiceTextType: "1",
    newAddressId: ''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var scanCode = decodeURIComponent(options.q)
    var oid = scanCode.substring(scanCode.lastIndexOf("=") + 1);
    this.setData({
      oid: oid
    })
    var that = this;
    if (app.globalData.accountInfo.uid) {
      that.orderInfo();
      that.addressList();
      that.setData({
        setLogin: "login"
      })
    } else {
      wx.getSetting({
        success: function (res) {
          if (res.authSetting['scope.userInfo']) {
            that.authorization();
          } else {
            that.setData({
              setLogin: "noLogin"
            })
          }
        }
      })
    }
  },

  onShow: function () {
    if (app.globalData.accountInfo.uid) {
      this.addressList();
    }
  },

  // 登录
  authorization: function () {
    var that = this
    wx.login({
      success: function (res_login) {
        wx.getUserInfo({
          withCredentials: true,
          success: function (res_user) {
            var login_code = res_login.code;
            var login_encryptedData = res_user.encryptedData;
            var login_iv = res_user.iv;
            that.autoLogin(login_code, login_encryptedData, login_iv);
            that.setData({
              setLogin: 'login'
            });
          }, fail: function (fail_res) {
            if (fail_res.errMsg == "getUserInfo:fail auth deny") {
              that.showModal();
            } else {
              util.showError("登录失败");
            }
          }
        })
      }, fail: function (fail_login) {
        //console.log("fail");
      }
    })
  },

  autoLogin: function (login_code, login_encryptedData, login_iv) {
    var that = this
    var params = {
      code: login_code,
      encryptedData: login_encryptedData,
      iv: login_iv
    }
    api.POST({
      params: params,
      url: app.globalData.login_url,
      success: function (res) {
        if (util.isEmpty(res.data.code)) {
          app.globalData.accountInfo = res.data.data.result;
          that.orderInfo();
          that.addressList();
        }
      },
      fail: function (fail) {
        util.showError("登录失败，请检查网络");
      }
    })
  },

  // 重新授权
  reAuthorization: function () {
    var that = this
    wx.openSetting({
      success: function (res) {
        if (res.authSetting["scope.userInfo"]) {
          //检测是否有登录信
            that.authorization();
        } else {
          that.showModal();
        }
      }
    })
  },

  showModal: function () {
    var that = this;
    wx.showModal({
      title: '警告',
      content: '若不授权，则无法使用',
      confirmText: '授权',
      cancelText: '不授权',
      success: function (suress) {
        if (suress.confirm) {
          that.reAuthorization();
        } else {
          that.showModal();
        }
      }
    })
  },

  // 订单信息
  orderInfo: function () {
    var that = this;
    api.POST({
      params: { oid: that.data.oid },
      url: app.globalData.base_url + 'couponsorder/info',
      success: function (res) {
        if (util.isEmpty(res.data.code)) {
          that.setData({
            orderInfo: res.data.data
          })
        } else {
          util.showError(res.data.message);
        }
      },
      fail: function (fail) {
        util.showError("网络错误");
      }
    })
  },

  //地址列表
  addressList: function () {
    var params = new Object()
    var that = this;
    api.POST({
      params: params,
      url: app.globalData.base_url + 'address/list',
      success: function (res) {
        if (util.isEmpty(res.data.code)) {
          var addressLength = res.data.data.address_list.length;
          var addressList = res.data.data.address_list;
          for (var i = 0; i < addressList.length; i++) {
            if (addressList[i].is_default == 1) {
              var addressId = addressList[i].aid
            }
          }

          that.setData({
            addressId: addressId,
            address: addressList,
            addressLength: addressLength
          })
        }
      },
      fail: function (fail) {
        util.showError("登录失败，请检查网络");
      }
    })
  },
  //添加新地址
  addAddress: function () {
    wx.navigateTo({
      url: '../addAddress/addAddress'
    })
  },
  //显示地址弹窗
  selAddress: function () {
    this.setData({
      addressCol: false
    })
  },
  //修改地址
  editorAddress: function (e) {
    var id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: '/pages/addAddress/addAddress?aid=' + id
    })
  },
  //删除地址
  deleteAddress: function (e) {
    var id = e.currentTarget.dataset.id;
    var that = this;

    wx.showModal({
      title: '提示',
      content: '确认删除该地址?',
      confirmColor: "#e51927",
      success: function (res) {
        if (res.confirm) {
          api.POST({
            params: { aid: id },
            url: app.globalData.base_url + 'address/del',
            success: function (res) {
              if (util.isEmpty(res.data.code)) {
                util.showStatus("删除成功")
                that.addressList();
              }
            },
            fail: function (fail) {
              util.showError("登录失败，请检查网络");

            }
          })
        } else if (res.cancel) {
          // console.log('用户点击取消')
        }
      }
    })
  },

  //选择地址
  radioChange: function (e) {
    var id = e.detail.value
    var that = this;
    that.setData({
      newAddressId: id
    })
  },

  //隐藏地址
  hiddenAddress: function () {
    var that = this;
    that.setData({
      addressCol: true,
      address: that.data.address
    })
  },
  //确认收货地址
  confirmAddress: function () {
    var that = this;
    if ((that.data.addressId != that.data.newAddressId) && (that.data.newAddressId != '')) {
      api.POST({
        params: {
          aid: that.data.newAddressId,
          is_default: 1
        },
        url: app.globalData.base_url + 'address/modify',
        success: function (res) {
          if (util.isEmpty(res.data.code)) {
            that.addressList();
            that.setData({
              addressCol: true,
              controlDome: true
            })
          } else {
            util.showError(res.data.message);
          }
        },
        fail: function (fail) {
          util.showError("网络错误");
        }
      })
    }

  },

  // 发票弹窗控制
  invoiceCol: function () {
    this.setData({
      invoice: false
    })
  },
  // 是否需要发票
  invoiceNeedCol: function (e) {
    this.setData({
      invoiceNeed: e.currentTarget.dataset.invoiceneed
    })
  },
  // 发票类型选择
  invoiceTypeCol: function (e) {
    this.setData({
      invoiceType: e.currentTarget.dataset.invoicetype
    })
  },
  // 发票抬头类型选择
  invoiceTextTypeCol: function (e) {
    this.setData({
      invoiceTextType: e.currentTarget.dataset.invoicetexttype
    })
  },
  // 企业名称输入
  EnameCol: function (e) {
    this.setData({
      Ename: e.detail.value
    })
  },
  // 纳税人识别号
  EnumberCol: function (e) {
    this.setData({
      Enumber: e.detail.value
    })
  },
  // 接收电子发票的邮箱
  EmailCol: function (e) {
    this.setData({
      Email: e.detail.value
    })
  },
  // 企业注册地址
  EaddressCol: function (e) {
    this.setData({
      Eaddress: e.detail.value
    })
  },
  // 企业电话号码
  phoneNumberCol: function (e) {
    this.setData({
      phoneNumber: e.detail.value
    })
  },
  // 企业开户银行
  bankNameCol: function (e) {
    this.setData({
      bankName: e.detail.value
    })
  },
  // 企业银行账号
  bankNumberCol: function (e) {
    this.setData({
      bankNumber: e.detail.value
    })
  },
  // 个人抬头名称
  nameCol: function (e) {
    this.setData({
      name: e.detail.value
    })
  },
  // 确认发票信息
  invoiceConfirm: function () {
    var invoiceType = this.data.invoiceType;
    if (this.data.invoiceNeed == 1) {  //是否需要发票
      if (invoiceType == 1) {
        this.setData({
          invoiceTypeCol: true
        })
      } else {
        this.setData({
          invoiceTypeCol: false
        })
      }
      this.invoiceTextTypeDecide();

    } else if (this.data.invoiceNeed == 0) {
      this.setData({
        invoice: true,
        invoiceTypeCol: false
      })
      return true
    }


  },
  // 个人或者企业发票判断
  invoiceTextTypeDecide: function () {
    if (this.data.invoiceTextType == 1) {  //个人发票
      this.invoiceTypeDecide();
    } else if (this.data.invoiceTextType = 2) {  //企业发票
      if (util.isEmpty(this.data.Ename)) {
        util.showStatus("请输入企业名称");
        return false
      }

      if (util.isEmpty(this.data.Enumber)) {
        util.showStatus("请输入纳税人识别号");
        return false
      }


      if (!util.isEmpty(this.data.phoneNumber)) {
        if (!util.validateMobile(this.data.phoneNumber)) {
          util.showStatus("企业电话号不正确");
          return false
        }
      }

      if (!util.isEmpty(this.data.bankNumber)) {
        if (util.isEmpty(this.data.bankName)) {
          util.showStatus("请输入开户行");
          return false
        }
        if (!util.checkBankNo(this.data.bankNumber)) {
          util.showStatus("银行账号不正确");
          return false
        }
      }

      this.invoiceTypeDecide();
    }
  },
  //发票类型判断
  invoiceTypeDecide: function () {
    if (this.data.invoiceType == 1) {  //普通发票
      this.setData({
        invoice: true
      })
      return true
    } else if (this.data.invoiceType = 2) {  //电子发票
      var email = this.data.Email;
      if (util.validateEmail(email)) {
        this.setData({
          invoice: true
        })
        return true
      } else {
        util.showStatus("邮箱地址错误");
        return false
      }
    }
  },

  // 更改订单发票信息
  payOrder: function () {
    var that = this;
    var params = new Object()
    params.oid = that.data.oid;

    if (this.data.invoiceNeed == 1) {  //是否需要发票
      //配送地址
      if (that.data.invoiceTypeCol) {
        var address = this.data.address
        for (var i = 0; i < address.length; i++) {
          if (address[i].is_default == 1) {
            params.aid = address[i].aid
          }
        }
        if (params.aid == undefined || params.aid == '') {
          util.showError("请选择收货地址");
          return false;
        }
      }

      if (this.data.invoiceTextType == 1) {  //个人发票

        params.invoice = "个人";
        if (this.data.invoiceType == 2) {  //电子发票
          params.invoice_email = this.data.Email;
          params.invoice_type = 2
        } else {
          params.invoice_type = 1
        }

      } else if (this.data.invoiceTextType == 2) {  //企业发票
        params.invoice = this.data.Ename;
        params.invoice_number = this.data.Enumber;
        if (this.data.invoiceType == 2) {  //电子发票
          params.invoice_email = this.data.Email;
          params.invoice_type = 2
        } else {
          params.invoice_type = 1
        }

        if (!util.isEmpty(this.data.Eaddress)) {
          params.invoice_e_r_address = this.data.Eaddress
        }

        if (!util.isEmpty(this.data.phoneNumber)) {
          params.invoice_e_tel = this.data.phoneNumber
        }

        if (!util.isEmpty(this.data.bankNumber)) {
          params.invoice_e_bank_name = this.data.bankName
          params.invoice_e_bank_number = this.data.bankNumber
        }
      }
      //添加发票
      api.POST({
        params: params,
        url: app.globalData.base_url + 'order/addInvoice',
        success: function (res) {
          if (util.isEmpty(res.data.code)) {
            that.wxPayOrder();
          } else {
            util.showError(res.data.message);
          }
        },
        fail: function (fail) {
          util.showError("网络错误");
        }
      })
    } else {
      that.wxPayOrder();
    }
  },

  // 订单支付
  wxPayOrder: function () {
    var that = this;
    api.POST({
      params: { oid: that.data.oid },
      url: app.globalData.base_url + 'payment/getWechatInfo',
      success: function (res) {
        if (util.isEmpty(res.data.code)) {

          var preData = res.data.data.payinfo;
          wx.requestPayment({
            timeStamp: preData.timeStamp,
            nonceStr: preData.nonceStr,
            package: preData.package,
            signType: preData.signType,
            paySign: preData.paySign,
            success: function (res) {
              wx.redirectTo({
                url: '../machinePaySuccess/machinePaySuccess?oid=' + that.data.oid
              })
            },
            fail: function (error) {
              util.showError("支付失败");
            }
          })
        } else {
          util.showError(res.data.message);
        }
      },
      fail: function (fail) {
        util.showError("网络错误");
      }
    })
  },

  // 获取微信发票信息
  obtainInvoice: function () {
    var that = this;
    wx.chooseInvoiceTitle({
      success(res) {
        console.log(res);
        var types = res.type,
          title = res.title,
          telephone = res.telephone,
          taxNumber = res.taxNumber,
          companyAddress = res.companyAddress,
          bankName = res.bankName,
          bankAccount = res.bankAccount

        if (that.data.invoiceTextType == 2) {
          if (types == 0) {
            that.setData({
              Ename: title,
              Enumber: taxNumber,
              Eaddress: companyAddress,
              bankName: bankName,
              bankNumber: bankAccount
            })
          } else {
            util.showError("抬头类型错误");
          }
        }
      },
      fail: function (fail) {
        if (fail.errMsg == 'chooseInvoiceTitle:fail:auth denied') {
          that.invoiceShowModal();
        }
      }
    })
  },

  invoiceShowModal: function () {
    var that = this;
    wx.showModal({
      title: '警告',
      content: '若不授权，则无法使用',
      confirmText: '授权',
      cancelText: '不授权',
      success: function (suress) {
        if (suress.confirm) {
          that.invoiceReAuthorization();
        }
      }
    })
  },
  // 重新授权
  invoiceReAuthorization: function () {
    var that = this
    wx.openSetting({
      success: function (res) {
        console.log(res)
        if (res.authSetting["scope.invoiceTitle"]) {
          that.obtainInvoice();
        }
      }
    })
  },
})